package stock

import (
	"github.com/axgle/mahonia"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
)

func ConvertToString(src string, srcCode string, tagCode string) string {
	srcCoder := mahonia.NewDecoder(srcCode)
	srcResult := srcCoder.ConvertString(src)
	tagCoder := mahonia.NewDecoder(tagCode)
	_, cdata, _ := tagCoder.Translate([]byte(srcResult), true)
	result := string(cdata)
	return result
}

func GetStockList() []string {
	var stockList = make([]string, 0, 6)
	stockList = append(stockList, "sz002232", "sz000812", "sz002951", "sz002432", "sz001317", "sh600559")
	return stockList
}

func GetStock() []map[string]string {
	s := strings.Join(GetStockList(), ",")
	url := "http://hq.sinajs.cn/list=" + s
	res, _ := http.Get(url)
	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)
	str := ConvertToString(string(body), "GB18030", "utf-8")

	return ExtractStock(str)
}
func ExtractStock(s string) []map[string]string {
	var stockMapList = make([]map[string]string, 0, 6)
	var j int
	stock := strings.Split(s, ";")
	for j = 0; j < len(stock)-1; j++ {
		stoc := strings.Split(stock[j], "=\"")
		data := strings.Split(stoc[1], ",")
		yesterday, _ := strconv.ParseFloat(data[2], 64)
		now, _ := strconv.ParseFloat(data[3], 64)
		rate := strconv.FormatFloat((now-yesterday)/yesterday*100, 'f', 2, 32)
		var stockMap map[string]string /*创建集合 */
		stockMap = make(map[string]string)
		stockMap["yesterdayPrice"] = data[2]
		stockMap["nowPrice"] = data[3]
		stockMap["rate"] = rate
		stockMap["stockName"] = data[0]
		stockMapList = append(stockMapList, stockMap)
	}
	return stockMapList
}
